package com.tianyu.jty.common.web;

import com.tianyu.jty.common.utils.StringUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.tianyu.jty.common.utils.Global.getConfig;

@Controller
@RequestMapping("common/")
public class FileUploadController {

  private static Logger logger = LoggerFactory.getLogger(FileUploadController.class);

  @RequestMapping(value = "uploadify")
  @ResponseBody
  public String saveFileupload(HttpServletRequest request, String menutree, HttpServletResponse response)
      throws UnsupportedEncodingException {

    Map map = new HashMap();
    request.setCharacterEncoding("utf-8");
    DiskFileItemFactory factory = new DiskFileItemFactory();
    String path = genDateRelaPath(getConfig("sys.upload.dir"));
    File fp = new File(path);
    // 创建目录
    if (!fp.exists()) {
      fp.mkdirs();// 目录不存在的情况下，创建目录。
    }
    factory.setRepository(new File(path));
    factory.setSizeThreshold(1024 * 1024);
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
      //可以上传多个文件
      List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
      for (FileItem item : list) {
        if (!item.isFormField()) {
          String name = item.getName();
          String fileSuffix = name.substring(name.lastIndexOf(".") + 1, name.length());
          String oldName = name.replaceAll("." + fileSuffix, "");
          String fileName = UUID.randomUUID().toString().replaceAll("-", "");
          String newName = fileName + "." + fileSuffix;
          OutputStream out = new FileOutputStream(new File(path, newName));
          InputStream in = item.getInputStream();
          int length = 0;
          byte[] buf = new byte[1024];
          while ((length = in.read(buf)) != -1) {
            out.write(buf, 0, length);
          }
          in.close();
          out.close();
          break;
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      return "上传失败";
    }
    return "上传成功";
  }

  @RequestMapping(value = "Huploadify")
  @ResponseBody
  public String saveFileuploadH5(HttpServletRequest request, MultipartFile file, HttpServletResponse response)
      throws UnsupportedEncodingException {

    String fileName = file.getOriginalFilename();

    try {
      DiskFileItemFactory factory = new DiskFileItemFactory();
      String path = genDateRelaPath(getConfig("sys.upload.dir"));
      File fp = new File(path);
      // 创建目录
      if (!fp.exists()) {
        fp.mkdirs();// 目录不存在的情况下，创建目录。
      }
      if (StringUtils.isNotBlank(fileName)) {
        String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        String oldName = fileName.replaceAll("." + fileSuffix, "");
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "");
        String newName = newFileName + "." + fileSuffix;
        file.transferTo(new File(path + newName));
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      return "上传失败";
    }
    return "上传成功";
  }

  /*
  * 文件下载
  */
  @RequestMapping(value = "downFile")
  @ResponseBody
  public void downFile(String id, HttpServletRequest request, HttpServletResponse response) {

//        List<Map<String, Object>> list = fileUploadService.downFile(id);
//        String filetype = String.valueOf(list.get(0).get("filetype"));
//        try {
////File file = new File(Constant.OPLOAD_PAHT,fileName);
//// 读到流中
//            InputStream inStream = new FileInputStream(list.get(0).get("filecontent") + "" + list.get(0).get("filename") + "" + "" + filetype + "");// 文件的存放路径
//// 设置输出的格式
//            response.reset();
//            response.setContentType("bin");
//            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(list.get(0).get("filename") + filetype, "UTF-8"));
//// 循环取出流中的数据
//            byte[] b = new byte[1000];
//            int len;
//
//            while ((len = inStream.read(b)) > 0)
//                response.getOutputStream().write(b, 0, len);
//            inStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
  }

  /**
   * 计算要保存相对路径
   *
   * @return
   */
  private static DateFormat df = new SimpleDateFormat("yyyyMMdd");

  public static String genDateRelaPath(String dir) {
    if (dir == null)
      dir = "upload/";
    if (dir.length() > 1 && '/' != dir.charAt(dir.length() - 1))
      dir += "/";

    String date = df.format(new Date());
    String path = dir + date + '/';
    return path;
  }
}
